<template>
  <div class="cspTest">
    <div class="cspTest-header">随堂测试</div>
    <div class="cspTest-body">
      <div class="cspTest-body-title">
        <!-- <button class="cspTest-body-title-btn" @click="get_source_list">
        </button> -->
      </div>
      <div class="cspTest-body-content">
        <div class="cspTest-body-content-tran">
          <div class="cspTest-body-content-tran-title">+从资源库选题</div>
          <div class="cspTest-body-content-tran-content">
            <a-transfer
              :data-source="mockData"
              :list-style="{
                width: '45%',
              }"
              :target-keys="targetKeys"
              @change="onChange"
            >
              <template
                slot="children"
                slot-scope="{
                  props: {
                    direction,
                    filteredItems,
                    selectedKeys,
                    disabled: listDisabled,
                  },
                  on: { itemSelectAll, itemSelect },
                }"
              >
                <a-table
                  :row-selection="
                    getRowSelection({
                      disabled: listDisabled,
                      selectedKeys,
                      itemSelectAll,
                      itemSelect,
                    })
                  "
                  :pagination="{
                    total: 10,
                    'hide-on-single-page': true,
                  }"
                  :columns="direction === 'left' ? leftColumns : rightColumns"
                  :data-source="filteredItems"
                  size="small"
                  :style="{ pointerEvents: listDisabled ? 'none' : null }"
                  :custom-row="
                    ({ key, disabled: itemDisabled }) => ({
                      on: {
                        click: () => {
                          if (itemDisabled || listDisabled) return;
                          itemSelect(key, !selectedKeys.includes(key));
                        },
                      },
                    })
                  "
                >
                  <template slot="operation" slot-scope="text, record">
                    <a-button type="link" @click.stop="showDetail(record)"
                      >查看</a-button
                    >
                  </template>
                </a-table>
              </template>
            </a-transfer>
          </div>
        </div>
      </div>
    </div>
    <!-- <a-row type="flex" justify="end">
      <a-col>
        <button class="content-btn" @click="node_vote">暂存事件</button>
      </a-col>
    </a-row> -->
  </div>
</template>

<script>
import difference from "lodash/difference";
import { mapState, mapGetters } from "vuex";

export default {
  props: {
    activityMessage: Object,
    publish: Number,
  },
  data() {
    return {
      // 穿梭框
      leftColumns: [
        {
          dataIndex: "title",
          title: "题目",
        },
        {
          title: "操作",
          align: "center",
          scopedSlots: { customRender: "operation" },
        },
      ],
      rightColumns: [
        {
          dataIndex: "title",
          title: "题目",
        },
        {
          title: "操作",
          align: "center",
          scopedSlots: { customRender: "operation" },
        },
      ],
      //

      mockData: [],
      targetKeys: [],
      //
      pagination: {
        pageSize: 5,
        showQuickJumper: true,
      },
      selectvisible: false,
      /* 存在于
         所有可以选择的试题
       */
      source: [],

      /* 存在于nodes->node_contents里的（已经存在于prepareLesson里的）
          用于在当前页面显示
       */
      cards: [],
      showvisible: false,
      question: {},
    };
  },
  computed: {
    ...mapGetters({
      test: "teacher/getTest",
    }),
    // selectedsource() {
    //   return this.source.filter((item) => item.selected);
    // },
    lesson_id() {
      return this.$route.query.lessonId;
    },
    teacher_id() {
      return this.$store.state.public.uid;
    },
  },
  methods: {
    // 穿梭框
    showDetail(record) {
      this.showvisible = true;
      this.question = record;
    },
    getMock() {
      let mockData = [];
      // let data = {
      //   key: i.toString(),
      //   title: `content${i + 1}`,
      //   description: `description of content${i + 1}`,
      //   chosen: Math.random() * 2 > 1,
      // };
      this.source.forEach((item, index) => {
        mockData.push({
          key: index.toString(),
          title: item.stem,
          ...item,
        });
      });
      this.mockData = mockData;
      // 处理已选择数据初始值，如果数据库中存在数据则渲染，否则为空
      let targetStatus;
      this.targetKeys = mockData
        .map((data) => {
          targetStatus = false;
          this.activityMessage.node_contents.forEach((node_content) => {
            if (node_content.title == data.title) {
              targetStatus = true;
            }
          });
          if (targetStatus) {
            return data.key;
          }
        })
        .filter((item) => {
          return item;
        });
    },
    onChange(nextTargetKeys) {
      this.targetKeys = nextTargetKeys;
      this.activityMessage.node_contents = [];
      this.targetKeys.forEach((target) => {
        this.activityMessage.node_contents.push({
          options: this.mockData[target].option,
          question_type: 2,
          right_answer: this.mockData[target].answer,
          title: this.mockData[target].title,
        });
      });
    },
    //
    getRowSelection({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: (item) => ({
          props: { disabled: disabled || item.disabled },
        }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter((item) => !item.disabled)
            .map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys);
          itemSelectAll(diffKeys, selected);
        },
        onSelect({ key }, selected) {
          itemSelect(key, selected);
        },
        selectedRowKeys: selectedKeys,
      };
    },
    get_source_list() {
      this.selectvisible = true;
    },
    node_vote() {
      try {
        const node_contents = this.selectedsource.map((item, index) => {
          return {
            options: item.option,
            question_type: item.multiple ? 3 : 2,
            right_answer: item.answer,
            title: item.stem,
          };
        });
        this.$store.commit("teacher/updateNodeContents", node_contents);
        this.$message.info("暂存成功");
      } catch (err) {
        this.$message.error("暂存失败");
        console.log(err);
      }
    },
    selectsource() {
      this.selectvisible = false;
    },
    showit(item) {
      this.showvisible = true;
      this.question = item;
    },
    deleteit(item) {
      item.selected = !item.selected;
    },
  },
  filters: {
    charFormatter(index) {
      return String.fromCharCode(65 + index);
    },
    multipleFormatter(multiple) {
      return multiple ? "多选题" : "单选题";
    },
  },
  mounted() {
    this.cards = this.test;
    this.$store
      .dispatch("teacher/getquestionBank", {
        lesson_id: this.lesson_id,
        teacher_id: this.teacher_id,
      })
      .then(() => {
        this.source = this.$store.getters["teacher/getQuestionList"];
        // 穿梭框数据
        this.getMock();
      });
  },
};
</script>
<style lang="scss">
.testtest {
  color: brown;
}
.custom-item {
  margin: 10px 0;
}
.optionLook {
  float: right;
}
</style>
